<?php
	$root = $_SERVER['DOCUMENT_ROOT'];
	include($root . "/util/session.php");//checks that the user is logged in
	include($root . "/util/privilege_check.php");
	checkPrivilege("admin");
	if($_SERVER["REQUEST_METHOD"] == "POST"){
		$degreeID=mysqli_real_escape_string($db,$_POST['degreeID']);
		$subjectID=mysqli_real_escape_string($db,$_POST['subjectID']);
		$studentID=mysqli_real_escape_string($db,$_POST['studentID']);
		$sql_query="select * from students_subjects where degreeID = '$degreeID' and subjectID='$subjectID' and studentID='$studentID'";
		$result=mysqli_query($db,$sql_query);
		//check if user exists
		if(mysqli_num_rows($result) != 0){
			$error="Relation exists";
		}
		else{
			$sql_query="INSERT INTO students_subjects (`degreeID`, `subjectID`, `studentID`) VALUES ('$degreeID', '$subjectID', '$studentID')";
			$result=mysqli_query($db,$sql_query);
			if($result){
				header("Location: /admin/admin.php?msg=Student added to subject");
			}
			else{
				$error="sql error";
				echo $sql_query;
			}
		}
	}
	else{
		$degreeID=mysqli_real_escape_string($db,$_GET['degreeID']);
		$studentID=mysqli_real_escape_string($db,$_GET['studentID']);
		$subjectID=mysqli_real_escape_string($db,$_GET['subjectID']);
	}
?>

<html>
<head>
	<title>Add a student to subject</title>
  	<link rel="stylesheet" type="text/css" href="adminStyle.css">
</head>
<body>
  	<?php
  	include($root . "/admin/header.php");
	?>
	<li><a href="/admin/subjectsStudentsList.php?subjectID=<?php echo $subjectID?>&&degreeID=<?php echo $degreeID?>">Back</a></li>
	<form action="/admin/subjectStudentAdd.php" method="post" id="subjectForm">
		<label for="degreeID">Degree ID:</label><br>
		<input type="text" id="degreeID" name="degreeID" value="<?php echo $degreeID ?>"><br>
		<label for="subjectID">Subject ID:</label><br>
		<input type="text" id="subjectID" name="subjectID" value="<?php echo $subjectID ?>"><br>
		<label for="studentID">Student:</label><br>
		<select name="studentID" id="studentID" name="studentID" form="subjectForm">
			<?php
				$tSQL="select * from users join user_info on users.username=user_info.login where usertype='student'";
				$tResult=mysqli_query($db,$tSQL);
				while($student=mysqli_fetch_assoc($tResult)){
					echo '<option value="' . $student['username'] . '">' . $student['full_name'] . '</option>';
				}
			?>
		</select>
		<input type="submit" value="Submit">
	</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php if(isset($error)){echo $error;} ?></div>

	<?php
  	include($root . "/admin/footer.php");
	?>
</body>
</html>
